package com.pliu.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.pliu.io.Resources;
import com.pliu.pojo.Configuration;
import com.pliu.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @ClassName XMLConfigBuilder
 * @Description dom4j解析类
 * @Author pliu
 * @Date 2020/6/21 10:22
 * @Version 1.0
 **/
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 解析数据库配置信息
     * @param in
     * @return
     */
    public Configuration parseConfig(InputStream in) throws Exception {
        //1,解析datasource
        Document document = new SAXReader().read(in);
        Element root = document.getRootElement();

        List<Element> list = root.selectNodes("//property");
        Properties properties = new Properties();
        for (Element element : list) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }
        //2,创建数据源
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(properties.getProperty("dirverClass"));
        dataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        dataSource.setUser(properties.getProperty("username"));
        dataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(dataSource);
        //3,mapper.xml解析
        List<Element> mappers = root.selectNodes("//mapper");
        for (Element element : mappers) {
            String mapperPath = element.attributeValue("resource");
            InputStream rs = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(rs);
        }

        return configuration;
    }
}
